package com.banzhi.shop.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.RelativeLayout;

import com.banzhi.shop.R;
import com.banzhi.shop.activity.CheckstandActivity;
import com.banzhi.shop.activity.ChoiceCheckstandActivity;
import com.banzhi.shop.activity.ChoiceOrderActivity;
import com.banzhi.shop.activity.ChoiceRefundRequestActivity;
import com.banzhi.shop.activity.OrderManagementActivity2;
import com.banzhi.shop.activity.RefundRequestActivity;
import com.banzhi.shop.adapter.ChoiceOrderManagementAdapter;
import com.banzhi.shop.adapter.OrderManagementAdapter;
import com.banzhi.shop.entity.OrderAffirm.OrderAffirm;
import com.banzhi.shop.entity.OrderManagement.Order_Data;
import com.banzhi.shop.entity.RefundRequest.Refund_Data;
import com.banzhi.shop.model.CallBack.DeleteOrderCallBack;
import com.banzhi.shop.model.CallBack.OrdersManagementCallBack;
import com.banzhi.shop.model.CallBack.RefundRequestCallBack;
import com.banzhi.shop.model.IDeleteOrderModel;
import com.banzhi.shop.model.IOrderManagementModel;
import com.banzhi.shop.model.IRefundRequestModel;
import com.banzhi.shop.model.Impl.ChoiceDeleteOrderImpl;
import com.banzhi.shop.model.Impl.ChoiceOrderManagementImpl;
import com.banzhi.shop.model.Impl.ChoiceRefundRequestImpl;
import com.banzhi.shop.model.Impl.DeleteOrderImpl;
import com.banzhi.shop.model.Impl.OrderManagementImpl;
import com.banzhi.shop.model.Impl.RefundRequestImpl;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.view.ListViewForScrollView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2018/11/12.
 */

public class ChoiceOrderFrg extends LazyLoadFragment implements OrdersManagementCallBack, SwipeRefreshLayout.OnRefreshListener, RefundRequestCallBack, DeleteOrderCallBack {
    /**
     * 选项卡的status 用来展现不同的界面
     */
    private String status;
   // private IOrderManagementModel model;
    private List<Order_Data> orderdata = new ArrayList<>();
    private SwipeRefreshLayout srllistview;
    private ListViewForScrollView listView;
    private ChoiceOrderManagementAdapter adapter;
    private RelativeLayout rlnodata;
    private int page = 1;
    /**
     * 判断listview是不是滑到最低端了
     */
    private boolean isbottom;
    private int position;

    /**
     * 申请退款的接口
     */
   // private IRefundRequestModel requestModel;
    private ChoiceOrderActivity activity;
    private int type = 0;
   // private IDeleteOrderModel deleteOrderModel;
    private ChoiceOrderManagementImpl model;
    private ChoiceRefundRequestImpl requestModel;
    private ChoiceDeleteOrderImpl deleteOrderModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取传过来的fragment的id
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            status = bundle.getString("status");
        }
    }


    @Override
    public int getLayout() {
        return R.layout.frg_order;
    }

    @Override
    public void initViews(View view) {
        activity = (ChoiceOrderActivity) getActivity();
        type = activity.getType();
        srllistview = (SwipeRefreshLayout) view.findViewById(R.id.srlayout);
        listView = (ListViewForScrollView) view.findViewById(R.id.listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srllistview.setOnRefreshListener(this);
        rlnodata = (RelativeLayout) view.findViewById(R.id.rl_nodata);
        setListeners();
        //model = new OrderManagementImpl();
        model = new ChoiceOrderManagementImpl();
      //  requestModel = new RefundRequestImpl();
        requestModel = new ChoiceRefundRequestImpl();
      //  deleteOrderModel = new DeleteOrderImpl();
        deleteOrderModel = new ChoiceDeleteOrderImpl();
    }

    @Override
    public void loadData() {
        LoadingDialogUtils.showProgress(getContext(), "正在加载,请稍后~");
        model.getOrderData(type, status, page, this);
    }

    private void setListeners() {
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && isbottom) {
                    page++;
                    LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                    model.getOrderData(type, status, page, ChoiceOrderFrg.this);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    isbottom = true;
                } else {
                    isbottom = false;
                }
            }
        });
    }

    public static ChoiceOrderFrg newInstance(String status) {
        Bundle bundle = new Bundle();
        bundle.putString("status", status);
        ChoiceOrderFrg testFm = new ChoiceOrderFrg();
        testFm.setArguments(bundle);
        return testFm;
    }

    /**
     * 展示列表
     */
    private void ShowData() {
        if (adapter == null) {
            adapter = new ChoiceOrderManagementAdapter(getActivity(), orderdata);
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.getcallback(new ChoiceOrderManagementAdapter.zhifuCallBack() {
            @Override
            public void zhifu(String id, int position) {
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.zhifu(id, ChoiceOrderFrg.this);
                ChoiceOrderFrg.this.position = position;
            }
            /**
             * 取消订单
             * @param id
             * @param position
             */
            @Override
            public void delete(String id, int position) {
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.delete(id, ChoiceOrderFrg.this);
                ChoiceOrderFrg.this.position = position;
            }

            @Override
            public void queren(String id, int position) {
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                model.shouhuo(id, ChoiceOrderFrg.this);
                ChoiceOrderFrg.this.position = position;
            }

            @Override
            public void tuikuan(String id, int position) {
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                requestModel.getData(id, ChoiceOrderFrg.this);
                ChoiceOrderFrg.this.position = position;
            }

            /**
             * 删除订单
             * @param id
             * @param position
             */
            @Override
            public void deleteorder(String id, int position) {
                LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
                deleteOrderModel.deleteOrder(id, ChoiceOrderFrg.this);
                ChoiceOrderFrg.this.position = position;
            }
        });

    }

    /**
     * @param object 获取订单信息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        LoadingDialogUtils.dismiss();
        if (page == 1) {
            orderdata.clear();
        } else {
            if (((List<Order_Data>) object).size() == 0) {
//                ToastUtils.makeToastShort("没有更多了");
                return;
            }
        }
        orderdata.addAll((List<Order_Data>) object);
        log.d("orderdata", orderdata.toString());
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        ShowData();
        LoadingDialogUtils.dismiss();
    }


    /**
     * @param object 获取订单信息失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
        LoadingDialogUtils.dismiss();
    }

    /**
     * @param object 支付成功
     */
    @Override
    public void zhifuSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        OrderAffirm data = (OrderAffirm) object;
        Intent intent = new Intent(getActivity(), ChoiceCheckstandActivity.class);
        intent.putExtra("orderid", orderdata.get(position).getId());
        intent.putExtra("goodprice", data.getRes().getOrderInfo().getPrice());
        intent.putExtra("balance", data.getRes().getBalance());
        intent.putExtra("bianma", data.getRes().getOrderInfo().getOrdersn());
        startActivity(intent);
        getActivity().finish();
    }

    /**
     * @param object 支付失败
     */
    @Override
    public void zhifuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 取消订单成功
     */
    @Override
    public void deleteOrderSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
        ToastUtils.makeToastShort("取消订单成功");
    }

    /**
     * @param object 取消订单失败
     */
    @Override
    public void deleteOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 确认收货成功
     */
    @Override
    public void querenOrderSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 确认收货失败
     */
    @Override
    public void querenOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    @Override
    public void onRefresh() {
        page = 1;
        LoadingDialogUtils.showProgress(getActivity(), "正在加载,请稍后~");
        model.getOrderData(type, status, page, this);
    }

    /**
     * 申请退款成功
     *
     * @param object
     */
    @Override
    public void onrefundrequestSuccess(Object object) {
        Refund_Data refund = (Refund_Data) object;
        Intent RRintent = new Intent(getActivity(), ChoiceRefundRequestActivity.class);
        RRintent.putExtra("data", refund);
        RRintent.putExtra("Orderid", orderdata.get(position).getId());
        RRintent.putExtra("status", orderdata.get(position).getStatus());
        startActivity(RRintent);
    }

    /**
     * 申请退款失败
     *
     * @param object
     */
    @Override
    public void onrefundrequestError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * 删除订单成功
     *
     * @param object
     */
    @Override
    public void deleteSuccess(Object object) {
        orderdata.remove(position);
        if (orderdata.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        adapter.notifyDataSetChanged();
        ToastUtils.makeToastShort("删除订单成功");
    }

    /**
     * 删除订单失败
     *
     * @param object
     */
    @Override
    public void deleteError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(getActivity(), jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }
}
